<template>
  <div class="top-right-btn" :style="style">
    <el-row>
      <!-- <el-tooltip class="item" effect="dark" :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top" v-if="search">
        <el-button circle icon="Search" @click="toggleSearch()" />
      </el-tooltip> -->
      <el-tooltip class="item" effect="dark" content="刷新" placement="top">
        <el-button circle icon="Refresh" @click="refresh()" />
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="设置列" placement="top" v-if="name">
        <el-button circle icon="Menu" @click="tooltipClick" />
      </el-tooltip>
    </el-row>
  </div>
  <el-drawer v-model="drawer" :close-on-click-modal="false">
    <template #header>
      <h4>列设置 - 资料视角</h4>
    </template>
    <template #default>
      <div class="content">
        <div class="content_div">
          <el-input v-model="leftSearch" style="width: 100%" placeholder="搜索隐藏列字段" :prefix-icon="Search"
            @keyup="handleQueryLeft" />
          <div class="title">已隐藏列</div>
          <el-tree ref="columnRef" :data="leftColumns" show-checkbox @check="addShow" node-key="key" class="left_tree"
            :props="{ label: 'label', children: 'children' }"></el-tree>
        </div>
        <div class="content_div">
          <el-input v-model="rightSearch" style="width: 100%" placeholder="搜索已显示字段" :prefix-icon="Search"
            @keyup="handleQueryRight" />
          <div class="right_div">

            <div class="title">已固定列</div>
            <el-tree ref="columnRef" :data="fixedColumns" show-checkbox @check="chanelShow" node-key="key"
              :props="{ label: 'label', children: 'children' }" :default-checked-keys="defaultCheckedFixed" draggable
              :allow-drop="allowDrop" @node-drag-start="dragStartFixed" @node-drag-end="dragEndFixed">
              <template #default="{ node, data }">
                <span class="custom-tree-node" @mouseenter="updateShowIcon(data, true)"
                  @mouseleave="updateShowIcon(data, false)">
                  <svg-icon icon-class="icon_liugedian" />
                  <span :style="{ 'color': node.data.key + 1 == currentIdFixed ? '#0094FF' : '' }"> {{ node.label }}</span>
                  <div class="svg_right" v-show="data.iconShowbtn" @click="goNoFixed(data)">
                    <svg-icon icon-class="icon_zhidingzhengde" />
                  </div>
                </span>
              </template>
            </el-tree>


            <div class="title">已显示列</div>
            <el-tree ref="columnRef" :data="rightColumns" show-checkbox @check="chanelShow" node-key="key"
              :props="{ label: 'label', children: 'children' }" :default-checked-keys="defaultCheckedRight" draggable
              :allow-drop="allowDrop" @node-drag-start="dragStart" @node-drag-end="dragEnd">
              <template #default="{ node, data }">
                <span class="custom-tree-node" @mouseenter="updateShowStatus(data, true)"
                  @mouseleave="updateShowStatus(data, false)">
                  <svg-icon icon-class="icon_liugedian" />
                  <span :style="{ 'color': node.data.key + 1 == currentId ? '#0094FF' : '' }">
                    {{ node.label }}</span>
                  <div class="svg_right" v-show="data.ifShowbtn" @click="goFixed(data)">
                    <svg-icon icon-class="icon_zhidingxiede" />
                  </div>
                </span>
              </template>
            </el-tree>

          </div>
        </div>
      </div>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancelClick">取消</el-button>
        <el-button type="primary" @click="confirmClick">保存</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { Search } from '@element-plus/icons-vue'
import { propTypes } from '@/utils/propTypes';
import { listColumn, addColumn,updateColumn } from '@/api/system/column/index'
const { proxy } = getCurrentInstance() as ComponentInternalInstance
const props = defineProps({
  showSearch: propTypes.bool.def(true),
  name: propTypes.string.def(),
  search: propTypes.bool.def(true),
  gutter: propTypes.number.def(10),
})
const columnRef = ref<ElTreeInstance>();
const emits = defineEmits(['update:showSearch', 'queryTable', 'updateColumn']);

const style = computed(() => {
  const ret: any = {};
  if (props.gutter) {
    ret.marginRight = `${props.gutter / 2}px`;
  }
  return ret;
});
// 弹窗展示
const drawer = ref(false)
// 左侧模糊搜索
const leftSearch = ref()
// 右侧模糊搜索
const rightSearch = ref()
// 拖拽样式
const currentId = ref('')
// 固定列拖拽样式
const currentIdFixed = ref('')
// 默认columns与定制columns集合
const typesColumns: any = ref()
// 左侧columns
const leftColumns: any = ref()
// 左侧columns用于搜索
const leftColumnsCopy = ref()
// 固定columns
const fixedColumns = ref()
// 固定columns用于搜索
const fixedColumnsCopy = ref()
// 右侧下方展示columns
const rightColumns: any = ref()
// 右侧下方展示columns用于搜索
const rightColumnsCopy: any = ref()
// 右侧默认选中节点
const defaultCheckedRight = ref([])
watch(rightColumns, (newVal) => {
  nextTick(() => {
    if(newVal){
      defaultCheckedRight.value = newVal.map((item: any) => item.key);
    }
  })
}, { deep: true, immediate: true });
// 固定列默认选中节点
const defaultCheckedFixed = ref([])
watch(fixedColumns, (newVal) => {
  nextTick(() => {
    if(newVal){
      defaultCheckedFixed.value = newVal.map((item: any) => item.key);
    }
  })
}, { deep: true, immediate: true });

// 列点击
const tooltipClick = async () => {
  drawer.value = true
  const { data } = await listColumn({ columnName: props.name })
  data.forEach((item: any) => item.columnCustom = JSON.parse(item.columnCustom))
  typesColumns.value = data
  // 默认colmun
  const leftdatas = data.filter((item: any) => item.isDefault == 1)
  // 个性化colmun集合
  const rightDatas = data.filter((item: any) => item.isDefault == 0)
  // 有个性化设置
  if (rightDatas.length > 0) {
    // 防止个性化后 默认列删除某一项列数据
    var rightDatasFilter = rightDatas[0].columnCustom.filter((item: any) => {
      return leftdatas[0].columnCustom.findIndex((it: any) => item.label == it.label) !== -1
    })
    fixedColumns.value = rightDatasFilter.filter((item: any) => item.fixed)
    fixedColumnsCopy.value = rightDatasFilter.filter((item: any) => item.fixed)
    rightColumns.value = rightDatasFilter.filter((item: any) => !item.fixed)
    rightColumnsCopy.value = rightDatasFilter.filter((item: any) => !item.fixed)
    leftColumns.value = leftdatas[0].columnCustom.filter((item: any) => {
      return rightDatas[0].columnCustom.findIndex((it: any) => item.label == it.label) == -1
    })
  } else {
    fixedColumns.value = leftdatas[0].columnCustom.filter((item: any) => item.fixed)
    fixedColumnsCopy.value = leftdatas[0].columnCustom.filter((item: any) => item.fixed)
    rightColumns.value = leftdatas[0].columnCustom.filter((item: any) => !item.fixed)
    rightColumnsCopy.value = leftdatas[0].columnCustom.filter((item: any) => !item.fixed)
    leftColumns.value = []
  }
  leftColumnsCopy.value = JSON.parse(JSON.stringify(leftColumns.value))

  leftSearch.value = ''
  rightSearch.value = ''
}
// 左侧搜索
const handleQueryLeft = () => {
  leftColumns.value = leftColumnsCopy.value?.filter((item: any) => item.label.includes(leftSearch.value))
}
// 右侧搜索
const handleQueryRight = () => {
  rightColumns.value = rightColumnsCopy.value?.filter((item: any) => item.label.includes(rightSearch.value))
  fixedColumns.value = fixedColumnsCopy.value?.filter((item: any) => item.label.includes(rightSearch.value))
}
// 设置拖拽只能到一级节点
const allowDrop = (draggingNode: any, dropNode: any, type: any) => {
  // 如果正在拖拽的节点是根节点，或者它的父节点就是根节点，则允许放置
  if (draggingNode.level === 1 || draggingNode.parent.level === 1) {
    return type !== 'inner'; // 不允许内部拖拽
  } else {
    return false; // 不允许拖拽到其他位置
  }
}
// 开始拖拽
const dragStart = (node: any, event: any) => {
  currentId.value = node.data.key + 1
}
// 固定列开始拖拽
const dragStartFixed = (node: any, event: any) => {
  currentIdFixed.value = node.data.key + 1
}
// 结束拖拽
const dragEnd = () => {
  currentId.value = ''
}
// 固定列结束拖拽
const dragEndFixed = () => {
  currentIdFixed.value = ''
}
// 划过显示
const updateShowStatus = (data: any, value: any) => {
  let keyStr = data.key
  function changeIfShowbtn(datas: any, keyStr: any) {
    if (datas.key === keyStr) {
      data.ifShowbtn = value
      return;
    }
  }
  for (let data of rightColumns.value) {
    changeIfShowbtn(data, keyStr);
  }
}
// 划过显示
const updateShowIcon = (data: any, value: any) => {
  let keyStr = data.key
  function changeIfShowbtn(datas: any, keyStr: any) {
    if (datas.key === keyStr) {
      data.iconShowbtn = value
      return;
    }
  }
  for (let data of fixedColumns.value) {
    changeIfShowbtn(data, keyStr);
  }
}
// 设置固定列
const goFixed = (data: FieldOptions) => {
  data.fixed = true
  data.iconShowbtn = false
  const index = rightColumns.value.findIndex((item: any) => item.key === data.key);
  rightColumns.value.splice(index, 1)
  rightColumnsCopy.value.splice(index, 1)
  fixedColumns.value.push(data)
  fixedColumnsCopy.value.push(data)
}
// 取消固定列
const goNoFixed = (data: FieldOptions) => {
  data.fixed = false
  data.ifShowbtn = false
  const index = fixedColumns.value.findIndex((item: any) => item.key === data.key);
  fixedColumns.value.splice(index, 1)
  fixedColumnsCopy.value.splice(index, 1)
  rightColumns.value.push(data)
  rightColumnsCopy.value.push(data)
}
// 增加显示列
const addShow = (data: any) => {
  data.iconShowbtn = false
  data.ifShowbtn = false
  data.visible = true
  const index = leftColumns.value.findIndex((item: any) => item.key === data.key);
  leftColumns.value.splice(index, 1)
  leftColumnsCopy.value.splice(index, 1)
  rightColumns.value.push(data)
  rightColumnsCopy.value.push(data)
}
// 取消显示列
const chanelShow = (data: any) => {
  data.iconShowbtn = false
  data.ifShowbtn = false
  data.visible = false
  if (data.fixed) {
    data.fixed = false
    const index = fixedColumns.value.findIndex((item: any) => item.key === data.key);
    fixedColumns.value.splice(index, 1)
    fixedColumnsCopy.value.splice(index, 1)
  } else {
    const index = rightColumns.value.findIndex((item: any) => item.key === data.key);
    rightColumns.value.splice(index, 1)
    rightColumnsCopy.value.splice(index, 1)
  }
  leftColumns.value.push(data)
  leftColumnsCopy.value.push(data)
}
// 取消
const cancelClick = () => {
  drawer.value = false
}
// 保存
const confirmClick = async () => {
  if(typesColumns.value.length == 1){
    await addColumn({ columnName: props.name, isDefault: '0', columnCustom: JSON.stringify([...fixedColumns.value, ...rightColumns.value]) })
  }else{
    const columnId = typesColumns.value.filter((item: any)=>item.isDefault == '0')[0].columnId
    await updateColumn({columnCustom: JSON.stringify([...fixedColumns.value, ...rightColumns.value]), isDefault: '0', columnName: props.name,columnId: columnId })
  }
  proxy?.$modal.msgSuccess("操作成功");
  drawer.value = false
  emits('updateColumn')
}
// 刷新
function refresh() {
  emits("queryTable");
}
</script>

<style lang="scss" scoped>
.content {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;

  .content_div {
    width: 48%;
    height: 100%;

    .title {
      color: #868d9c;
      font-weight: 600;
      font-size: 14px;
      line-height: 16px;
      margin: 10px 0;
    }

    .left_tree {
      width: 100%;
      height: calc(100% - 70px);
      overflow: auto;
    }

    .right_div {
      width: 100%;
      height: calc(100% - 32px);
      overflow: auto;
    }

    :deep(.is-leaf) {
      display: none;
    }

    .custom-tree-node {
      display: flex;
      align-items: center;
      width: 100%;

      svg {
        width: 20px;
        padding-right: 7px;
      }

      .svg_right {
        flex: 1;
        padding: 0 !important;
        text-align: right;
      }
    }
  }
}


:deep(.el-transfer__button) {
  border-radius: 50%;
  display: block;
  margin-left: 0px;
}

:deep(.el-transfer__button:first-child) {
  margin-bottom: 10px;
}

.my-el-transfer {
  text-align: center;
}

.tree-header {
  width: 100%;
  line-height: 24px;
  text-align: center;
}

.show-btn {
  margin-left: 12px;
}
</style>
